define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'shopmoney/shoporder/index',
                    add_url: 'shopmoney/shoporder/add',
                    edit_url: 'shopmoney/shoporder/edit',
                    del_url: 'shopmoney/shoporder/del',
                    multi_url: 'shopmoney/shoporder/multi',
                    table: 'tuan_order',
                    commonSearch: false,
                }
            });

            var table = $("#table");
            //在普通搜索提交搜索前
            table.on('common-search.bs.table', function (event, table, params, query) {

                //这里可以对params值进行修改,从而影响搜索条件
                var filter = JSON.parse(params.filter);
                if(typeof filter.price !== 'undefined'){
                    filter.price *= 100;
                    params.filter = JSON.stringify(filter);
                }
            });
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'order_id',
                sortName: 'order_id',
                search: false,//快速搜索
                showToggle: false,
                showColumns: false,
                commonSearch: true, //是否启用通用搜索
                searchFormVisible: true, //是否始终显示搜索表单
                exportDataType: "all", //all导出整个表,basic导出当前分页
                exportTypes: [ 'csv','excel'],
                exportOptions:{
                    ignoreColumn: [],  //忽略某一列的索引
                    fileName: '店铺交易列表',//文件名称设置
                    worksheetName: 'sheet1',  //表格工作区名称
                    onMsoNumberFormat: function (cell, row, col) {
                        if(col <=11 && col >= 4){
                            return '0\.00';
                        }else{
                            return !isNaN($(cell).text())?'\\@':'';
                        }
                    }
                },
                columns: [
                    [
                        // {checkbox: true},
                        {field: 'shop_id', title: __('店铺id'),events: Controller.api.events.shop_id, formatter: Controller.api.formatter.shop_id,visible:false},
                        {field: 'order_id', title: __('编号'),operate:false},
                        {field: 'order_num', title: __('订单号')},
                        {field: 'tuaninfo.title', title: __('团购名称'),operate:'LIKE'},
                        {field: 'order_type', title: __('订单类型'),searchList: {'1': __('团购'), '2': __('买单')}, style: 'min-width:50px;'},
                        {field: 'original_price', title: __('原价（元）'),operate: false},
                        {field: 'total_price', title: __('交易金额（元）'),operate: false},
                        {field: 'discount', title: __('优惠抵扣券（元）'),operate: false},
                        {field: 'coupon_price', title: __('减免价（元）'),operate: false},
                        {field: 'integral', title: __('积分抵扣'),operate:false},
                        {field: 'price', title: __('实付金额（元）')},
                        {field: 'back_money', title: __('返现金额（元）'),operate:false},
                        {field: 'real_earnings', title: '实际收益（元）',operate:false},
                        {field: 'back_status', title: __('返现状态'),operate:false},
                        {field: 'pay_type', title: __('支付方式'),searchList: {'1': __('余额'), '2': __('支付宝'),'3':__('微信'),'4': __('现金支付')}, style: 'min-width:100px;'},
                        {field: 'pay_time', title: __('入账时间'),formatter: Table.api.formatter.datetime,
                            operate: 'RANGE',
                            addclass: 'datetimerange'},
                        {field: 'operate', title: __('Operate'), table: table,buttons: [
                            {name: 'detail', text: '查看详情', title: '查看详情', icon: 'fa fa-list', classname: 'btn btn-xs btn-info btn-dialog', url: 'shopmoney/shoporder/edit'},
                            // {name: 'detail', text: '测试跳转', extend:'order_num',title: '测试跳转', icon: 'fa fa-list',classname: 'btn btn-xs btn-info btn-dialog', url: 'tuan/billing/test'}
                        ], events: Table.api.events.buttons, formatter: Controller.api.formatter.btn}
                    ]
                ],

                queryParams: function (params) {
                    return {
                        search: params.search,
                        sort: params.sort,
                        order: params.order,
                        filter: params.filter,
                        op: params.op,
                        offset: params.offset,
                        limit: params.limit,
                    };
                },
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            formatter: {
                btn: function (value, row, index) {
                    var table = this.table;
                    // 操作配置
                    var options = table ? table.bootstrapTable('getOptions') : {};
                    // 默认按钮组
                    var buttons = $.extend([], this.buttons || []);
                    var html = [];
                    var url, classname, icon, text, title, extend,params;
                    $.each(buttons, function (i, j) {
                        var attr = table.data("buttons-" + j.name);
                        if (typeof attr === 'undefined' || attr) {
                            url = j.url ? j.url : '';
                            if (url.indexOf("{ids}") === -1) {
                                url = url ? url + (url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + row[options.pk] : '';
                            }
                            var params = options.urlJump;
                            if(typeof  params !== 'undefined'){
                                url += '&'+params+'='+row[params];
                            }
                            url = Table.api.replaceurl(url, value, row, table);
                            url = url ? Fast.api.fixurl(url) : 'javascript:;';
                            classname = j.classname ? j.classname : 'btn-primary btn-' + name + 'one';
                            icon = j.icon ? j.icon : '';
                            text = j.text ? j.text : '';
                            title = j.title ? j.title : text;
                            extend = j.extend ? j.extend : '';
                            html.push('<a href="' + url + '" class="' + classname + '" ' + extend + ' title="' + title + '"><i class="' + icon + '"></i>' + (text ? ' ' + text : '') + '</a>');
                        }
                    });
                    return html.join(' ');
                },
                shop_id: function (value, row, index) {
                    console.log(1);
                    return '<a class="btn btn-xs btn-ip bg-success"><i class="fa fa-map-marker"></i> ' + value + '</a>';
                },
            },
            events: {//绑定事件的方法
                shop_id: {
                    //格式为：方法名+空格+DOM元素
                    'click .btn-ip': function (e, value, row, index) {
                        e.stopPropagation();
                        var container = $("#table").data("bootstrap.table").$container;
                        var options = $("#table").bootstrapTable('getOptions');
                        //这里我们手动将数据填充到表单然后提交
                        $("form.form-commonsearch [name='shop_id']", container).val(value);
                        $("form.form-commonsearch", container).trigger('submit');
                        Toastr.info("执行了自定义搜索操作");
                    }
                },
                browser: {
                    'click .btn-browser': function (e, value, row, index) {
                        e.stopPropagation();
                        Layer.alert("该行数据为: <code>" + JSON.stringify(row) + "</code>");
                    }
                },
            }
        }
    };
    return Controller;
});